<?php
Yii::import('ext.widgets.ELike.LikeData');
class LikeButtonWidget extends Widget {

    public $model;
    public $route;
    public $buttonLabel = 'Like';
    public $activeButtonLabel = 'Unlike';
    public $activeCssClass = 'like-active';
    public $linkHtmlOptions = array('class' => 'like');
    public $labelHtmlOptions = array('class' => 'like-label');
    public $countHtmlOptions = array('class' => 'like-count');
    public $id;
    public $data;
    public $count = 0;
    public $template = '{link}{label} {count}{/link}';
    private $_isActive = false;

    /**
     * Initializes the widgets
     */
    public function init() {
        parent::init();
        if (empty($this->model)) {
            echo __CLASS__ . ': "model" is not assigned.';
            return;
        }

        if ($this->route === null)
            $this->route = 'ajax/like';// . strtolower(get_class($this->model));

        if ($this->id === null)
            $this->id = strtolower(implode('-', array(
                __CLASS__,
                get_class($this->model),
            )));

        if (Yii::app()->user->isGuest) {
            $this->data = array();
        } else {
            $this->data = LikeData::getData(get_class($this->model));
            $this->_isActive = isset($this->data[$this->model->id]) && $this->data[$this->model->id] == Option::STATUS_ACTIVE;
            $this->runScript();
        }
    }

    /**
     * Execute the widgets
     */
    public function run() {
        Yii::beginProfile(get_class($this));

        $pos = strpos($this->template, '{/link}');
        echo strtr($this->template, array(
            '{link}' => $pos === false ? $this->link() : str_replace('</a>', '', $this->link()),
            '{label}' => $this->label(),
            '{count}' => $this->count(),
            '{/link}' => '</a>',
        ));

        Yii::endProfile(get_class($this));
    }

    public function link() {
        $this->linkHtmlOptions['id'] = $this->id . '-' . $this->model->id;
        if ($this->_isActive)
            $this->linkHtmlOptions['class'] = implode(' ', array_filter(array(
                $this->id . '-' . $this->model->id,
                $this->linkHtmlOptions['class'],
                $this->activeCssClass,
            )));
        if (!Yii::app()->user->isGuest)
            $this->linkHtmlOptions['onClick'] = 'return ajaxLike' . get_class($this->model) . '(' . $this->model->id . ');';
        return CHtml::link('', Yii::app()->createUrl($this->route, array(
                            'id' => $this->model->id,
                            'module'=>get_class($this->model),
                        )), $this->linkHtmlOptions);
    }

    public function label() {
        $this->labelHtmlOptions['id'] = $this->id . '-label-' . $this->model->id;
        $this->labelHtmlOptions['class'] = $this->id . '-label-' . $this->model->id;
        $label = $this->_isActive ? $this->activeButtonLabel : $this->buttonLabel;
        return CHtml::openTag('span', $this->labelHtmlOptions)
                . $label
                . CHtml::closeTag('span');
    }

    public function count() {
        if ($this->count === null)
            return '';

        $this->countHtmlOptions['id'] = $this->id . '-count-' . $this->model->id;
        $this->countHtmlOptions['class'] = $this->id . '-count-' . $this->model->id;
        return CHtml::openTag('span', $this->countHtmlOptions)
                . $this->count
                . CHtml::closeTag('span');
    }

    private function runScript() {
        Yii::app()->clientScript->registerScript(__CLASS__ . get_class($this->model), '
                            
            function ajaxLike' . get_class($this->model) . '(id){
                formData=new FormData();
                formData.append("ajax","ajax");
                formData.append("YII_CSRF_TOKEN","'.Yii::app()->request->csrfToken.'");
                formData.append("module","'.get_class($this->model).'");
                formData.append("id", id);

                $.ajax({
                        url:"' . Yii::app()->createUrl($this->route) . '",
                        type:"POST",
                        data: formData,
                        dataType:"json",
                        success: function(data, textStatus, jqXHR){
                            if(data.result==1){
                                $(".' . $this->id . '-"+(id)).addClass("' . $this->activeCssClass . '");
                                $(".' . $this->id . '-label-"+(id)).html("' . $this->activeButtonLabel . '");
                                $(".' . $this->id . '-count-"+(id)).html(data.total);
                            }else{
                                $(".' . $this->id . '-"+(id)).removeClass("' . $this->activeCssClass . '");
                                $(".' . $this->id . '-label-"+(id)).html("' . $this->buttonLabel . '");
                                $(".' . $this->id . '-count-"+(id)).html(data.total);
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown){
                            alert(textStatus);
                        }
                    });
                e.preventDefault();
                return false;
            }
            ', CClientScript::POS_END);
    }

}
